import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';
import '../data/models/emotion_record.dart';
import '../data/repositories/emotion_repository.dart';
import '../data/repositories/emotion_repository_impl.dart';
import '../data/repositories/media_repository.dart' as media_repo;
import '../data/repositories/media_repository_impl.dart' as media_impl;

/// 历史记录控制器
/// History controller
class HistoryController extends GetxController {
  final EmotionRepository _emotionRepository = EmotionRepositoryImpl();
  final media_repo.MediaRepository _mediaRepository = media_impl.MediaRepositoryImpl();

  // 响应式状态变量
  // Reactive state variables
  final RxList<EmotionRecord> _allRecords = <EmotionRecord>[].obs;
  final RxList<EmotionRecord> _filteredRecords = <EmotionRecord>[].obs;
  final RxList<EmotionRecord> _selectedDateRecords = <EmotionRecord>[].obs;
  final RxMap<DateTime, List<EmotionRecord>> _recordsByDate = <DateTime, List<EmotionRecord>>{}.obs;
  
  final Rx<DateTime> _selectedDate = DateTime.now().obs;
  final Rx<DateTime> _focusedDate = DateTime.now().obs;
  final RxString _viewMode = 'calendar'.obs; // 'calendar' or 'list'
  final RxString _searchQuery = ''.obs;
  final RxSet<EmotionType> _selectedEmotionTypes = <EmotionType>{}.obs;
  final RxString _selectedTimeFilter = 'all'.obs; // 'all', 'today', 'week', 'month'
  final Rx<CalendarFormat> _calendarFormat = CalendarFormat.month.obs;
  final RxBool _isCalendarView = true.obs;
  
  final RxBool _isLoading = false.obs;
  final RxBool _hasMoreRecords = true.obs;
  final RxInt _currentPage = 0.obs;
  final RxInt _recordsPerPage = 20.obs;
  final RxString _errorMessage = ''.obs;
  
  // 搜索控制器
  // Search controller
  final TextEditingController searchController = TextEditingController();

  // Getters for accessing reactive state
  List<EmotionRecord> get allRecords => _allRecords;
  List<EmotionRecord> get filteredRecords => _filteredRecords;
  List<EmotionRecord> get selectedDateRecords => _selectedDateRecords;
  Map<DateTime, List<EmotionRecord>> get recordsByDate => _recordsByDate;
  
  DateTime get selectedDate => _selectedDate.value;
  DateTime get selectedDay => _selectedDate.value;
  DateTime get focusedDate => _focusedDate.value;
  String get viewMode => _viewMode.value;
  String get searchQuery => _searchQuery.value;
  Set<EmotionType> get selectedEmotionTypes => _selectedEmotionTypes;
  String get selectedTimeFilter => _selectedTimeFilter.value;
  Set<EmotionType> get selectedEmotionFilter => _selectedEmotionTypes;
  CalendarFormat get calendarFormat => _calendarFormat.value;
  bool get isCalendarView => _isCalendarView.value;
  DateTime get focusedDay => _focusedDate.value;
  
  bool get isLoading => _isLoading.value;
  bool get hasMoreRecords => _hasMoreRecords.value;
  int get currentPage => _currentPage.value;
  String get errorMessage => _errorMessage.value;
  
  // 刷新记录的getter
  Future<void> Function() get refreshRecords => refreshData;
  
  // 日历相关的getter
  void Function(DateTime, DateTime) get onDaySelected => selectDate;
  void Function(CalendarFormat) get onFormatChanged => (format) {};
  void Function(DateTime) get onPageChanged => (date) {};
  List<EmotionRecord> Function(DateTime) get getEventsForDay => (day) => getRecordsForDay(day);

  @override
  void onInit() {
    super.onInit();
    // 初始化时加载数据
    // Load data on initialization
    loadAllRecords();
    loadSelectedDateRecords();
  }

  /// 加载所有记录
  /// Load all records
  Future<void> loadAllRecords() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final records = await _emotionRepository.getAllRecords();
      _allRecords.assignAll(records);
      
      // 按日期分组记录
      // Group records by date
      _groupRecordsByDate(records);
      
      // 应用当前筛选条件
      // Apply current filters
      _applyFilters();
    } catch (e) {
      _errorMessage.value = '加载记录失败: ${e.toString()}';
      Get.snackbar('错误', '加载记录失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载指定日期的记录
  /// Load records for selected date
  Future<void> loadSelectedDateRecords() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final startOfDay = DateTime(
        _selectedDate.value.year,
        _selectedDate.value.month,
        _selectedDate.value.day,
      );
      final endOfDay = startOfDay.add(const Duration(days: 1));
      
      final records = await _emotionRepository.getRecordsByDateRange(
        startDate: startOfDay,
        endDate: endOfDay,
      );
      
      _selectedDateRecords.assignAll(records);
    } catch (e) {
      _errorMessage.value = '加载日期记录失败: ${e.toString()}';
      Get.snackbar('错误', '加载日期记录失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 分页加载记录
  /// Load records with pagination
  Future<void> loadMoreRecords() async {
    if (!_hasMoreRecords.value || _isLoading.value) return;
    
    try {
      _isLoading.value = true;
      
      final records = await _emotionRepository.getRecordsPaginated(
        page: _currentPage.value,
        pageSize: _recordsPerPage.value,
      );
      
      if (records.length < _recordsPerPage.value) {
        _hasMoreRecords.value = false;
      }
      
      _allRecords.addAll(records);
      _currentPage.value++;
      
      // 重新分组和筛选
      // Regroup and filter
      _groupRecordsByDate(_allRecords);
      _applyFilters();
    } catch (e) {
      _errorMessage.value = '加载更多记录失败: ${e.toString()}';
      Get.snackbar('错误', '加载更多记录失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 按日期分组记录
  /// Group records by date
  void _groupRecordsByDate(List<EmotionRecord> records) {
    final Map<DateTime, List<EmotionRecord>> grouped = {};
    
    for (final record in records) {
      final date = DateTime(
        record.createdAt.year,
        record.createdAt.month,
        record.createdAt.day,
      );
      
      if (!grouped.containsKey(date)) {
        grouped[date] = [];
      }
      grouped[date]!.add(record);
    }
    
    _recordsByDate.assignAll(grouped);
  }

  /// 设置选中的日期
  /// Set selected date
  void setSelectedDate(DateTime date) {
    _selectedDate.value = date;
    loadSelectedDateRecords();
  }

  /// 选择日期（日历回调方法）
  /// Select date (calendar callback method)
  void selectDate(DateTime selectedDay, DateTime focusedDay) {
    _selectedDate.value = selectedDay;
    _focusedDate.value = focusedDay;
    loadSelectedDateRecords();
  }

  /// 设置焦点日期（日历视图）
  /// Set focused date (calendar view)
  void setFocusedDate(DateTime date) {
    _focusedDate.value = date;
  }

  /// 设置搜索查询
  /// Set search query
  void setSearchQuery(String query) {
    _searchQuery.value = query;
    _applyFilters();
  }

  /// 切换情绪类型筛选
  /// Toggle emotion type filter
  void toggleEmotionTypeFilter(EmotionType emotionType) {
    if (_selectedEmotionTypes.contains(emotionType)) {
      _selectedEmotionTypes.remove(emotionType);
    } else {
      _selectedEmotionTypes.add(emotionType);
    }
    _applyFilters();
  }

  /// 清除所有筛选条件
  /// Clear all filters
  void clearFilters() {
    _searchQuery.value = '';
    _selectedEmotionTypes.clear();
    _applyFilters();
  }

  /// 应用筛选条件
  /// Apply filters
  void _applyFilters() {
    List<EmotionRecord> filtered = List.from(_allRecords);
    
    // 按搜索查询筛选
    // Filter by search query
    if (_searchQuery.value.isNotEmpty) {
      filtered = filtered.where((record) {
        return (record.diaryContent?.toLowerCase().contains(_searchQuery.value.toLowerCase()) ?? false) ||
               record.emotionType.label.toLowerCase().contains(_searchQuery.value.toLowerCase());
      }).toList();
    }
    
    // 按情绪类型筛选
    // Filter by emotion types
    if (_selectedEmotionTypes.isNotEmpty) {
      filtered = filtered.where((record) {
        return _selectedEmotionTypes.contains(record.emotionType);
      }).toList();
    }
    
    _filteredRecords.assignAll(filtered);
  }

  /// 设置视图模式
  /// Set view mode
  void setViewMode(String mode) {
    _viewMode.value = mode;
  }

  /// 获取指定日期的记录数量
  /// Get record count for specific date
  int getRecordCountForDate(DateTime date) {
    final dateKey = DateTime(date.year, date.month, date.day);
    return _recordsByDate[dateKey]?.length ?? 0;
  }

  /// 获取指定日期的主要情绪
  /// Get primary emotion for specific date
  EmotionType? getPrimaryEmotionForDate(DateTime date) {
    final dateKey = DateTime(date.year, date.month, date.day);
    final records = _recordsByDate[dateKey];
    
    if (records == null || records.isEmpty) return null;
    
    // 统计情绪类型出现次数
    // Count emotion type occurrences
    final Map<EmotionType, int> emotionCounts = {};
    for (final record in records) {
      emotionCounts[record.emotionType] = 
          (emotionCounts[record.emotionType] ?? 0) + 1;
    }
    
    // 返回出现次数最多的情绪
    // Return most frequent emotion
    EmotionType? primaryEmotion;
    int maxCount = 0;
    
    emotionCounts.forEach((emotion, count) {
      if (count > maxCount) {
        maxCount = count;
        primaryEmotion = emotion;
      }
    });
    
    return primaryEmotion;
  }

  /// 获取指定日期的平均情绪强度
  /// Get average emotion intensity for specific date
  double getAverageIntensityForDate(DateTime date) {
    final dateKey = DateTime(date.year, date.month, date.day);
    final records = _recordsByDate[dateKey];
    
    if (records == null || records.isEmpty) return 0.0;
    
    final totalIntensity = records.fold<double>(
      0.0,
      (sum, record) => sum + record.intensity,
    );
    
    return totalIntensity / records.length;
  }

  /// 删除记录
  /// Delete record
  Future<void> deleteRecord(String recordId) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      // 删除关联的媒体文件
      // Delete associated media files
      await _mediaRepository.deleteMediaFilesByRecordId(recordId);
      
      // 删除记录
      // Delete record
      await _emotionRepository.deleteRecord(recordId);
      
      // 从本地列表中移除
      // Remove from local lists
      _allRecords.removeWhere((record) => record.id == recordId);
      _filteredRecords.removeWhere((record) => record.id == recordId);
      _selectedDateRecords.removeWhere((record) => record.id == recordId);
      
      // 重新分组
      // Regroup
      _groupRecordsByDate(_allRecords);
      
      Get.snackbar('成功', '记录已删除', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '删除记录失败: ${e.toString()}';
      Get.snackbar('错误', '删除记录失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 获取记录详情（包含媒体文件）
  /// Get record details (including media files)
  Future<EmotionRecord?> getRecordWithMedia(String recordId) async {
    try {
      final record = await _emotionRepository.getRecordById(recordId);
      if (record != null) {
        // 获取媒体文件信息（如果需要的话）
        // Get media files information (if needed)
        await _mediaRepository.getMediaFilesByRecordId(recordId);
        return record;
      }
      return null;
    } catch (e) {
      _errorMessage.value = '获取记录详情失败: ${e.toString()}';
      return null;
    }
  }

  /// 获取连续记录天数
  /// Get consecutive recording days
  Future<int> getConsecutiveRecordingDays() async {
    try {
      return await _emotionRepository.getConsecutiveRecordingDays();
    } catch (e) {
      return 0;
    }
  }

  /// 获取本月记录统计
  /// Get current month statistics
  Map<String, dynamic> getCurrentMonthStats() {
    final now = DateTime.now();
    final startOfMonth = DateTime(now.year, now.month, 1);
    final endOfMonth = DateTime(now.year, now.month + 1, 0);
    
    final monthRecords = _allRecords.where((record) {
      return record.createdAt.isAfter(startOfMonth) && 
             record.createdAt.isBefore(endOfMonth.add(const Duration(days: 1)));
    }).toList();
    
    if (monthRecords.isEmpty) {
      return {
        'total_records': 0,
        'average_intensity': 0.0,
        'most_common_emotion': null,
        'recording_days': 0,
      };
    }
    
    // 计算平均强度
    // Calculate average intensity
    final averageIntensity = monthRecords.fold<double>(
      0.0,
      (sum, record) => sum + record.intensity,
    ) / monthRecords.length;
    
    // 统计最常见情绪
    // Count most common emotion
    final Map<EmotionType, int> emotionCounts = {};
    for (final record in monthRecords) {
      emotionCounts[record.emotionType] = 
          (emotionCounts[record.emotionType] ?? 0) + 1;
    }
    
    EmotionType? mostCommonEmotion;
    int maxCount = 0;
    emotionCounts.forEach((emotion, count) {
      if (count > maxCount) {
        maxCount = count;
        mostCommonEmotion = emotion;
      }
    });
    
    // 计算记录天数
    // Calculate recording days
    final recordingDates = monthRecords.map((record) => DateTime(
      record.createdAt.year,
      record.createdAt.month,
      record.createdAt.day,
    )).toSet();
    
    return {
      'total_records': monthRecords.length,
      'average_intensity': averageIntensity,
      'most_common_emotion': mostCommonEmotion,
      'recording_days': recordingDates.length,
    };
  }

  /// 刷新数据
  /// Refresh data
  Future<void> refreshData() async {
    _currentPage.value = 0;
    _hasMoreRecords.value = true;
    _allRecords.clear();
    _recordsByDate.clear();
    
    await loadAllRecords();
    await loadSelectedDateRecords();
  }

  /// 清除错误信息
  /// Clear error message
  void clearError() {
    _errorMessage.value = '';
  }

  /// 清除搜索
  /// Clear search
  void clearSearch() {
    searchController.clear();
    _searchQuery.value = '';
    _applyFilters();
  }

  /// 搜索记录
  /// Search records
  void searchRecords() {
    _searchQuery.value = searchController.text;
    _applyFilters();
  }

  /// 设置时间过滤器
  /// Set time filter
  void setTimeFilter(String filter) {
    _selectedTimeFilter.value = filter;
    _applyFilters();
  }

  /// 获取选中日期的记录
  /// Get records for selected day
  List<EmotionRecord> getRecordsForSelectedDay() {
    final selectedDateKey = DateTime(
      _selectedDate.value.year,
      _selectedDate.value.month,
      _selectedDate.value.day,
    );
    return _recordsByDate[selectedDateKey] ?? [];
  }

  /// 跳转到记录详情
  /// Go to record detail
  void goToRecordDetail(String recordId) {
    Get.toNamed('/record-detail', arguments: {'recordId': recordId});
  }
  
  // 设置情绪过滤器
  void setEmotionFilter(Set<EmotionType> emotions) {
    _selectedEmotionTypes.assignAll(emotions);
    _applyFilters();
  }
  
  // 获取指定日期的记录
  List<EmotionRecord> getRecordsForDay(DateTime day) {
    final dayKey = DateTime(day.year, day.month, day.day);
    return _recordsByDate[dayKey] ?? [];
  }
  
  // 切换视图模式
  void toggleViewMode() {
    _isCalendarView.value = !_isCalendarView.value;
  }

  /// 导航到今天
  /// Navigate to today
  void goToToday() {
    final today = DateTime.now();
    setSelectedDate(today);
    setFocusedDate(today);
  }

  /// 导航到指定月份
  /// Navigate to specific month
  void goToMonth(DateTime month) {
    setFocusedDate(month);
  }

  /// 获取日历标记数据
  /// Get calendar marker data
  Map<DateTime, List<dynamic>> getCalendarMarkers() {
    final Map<DateTime, List<dynamic>> markers = {};
    
    _recordsByDate.forEach((date, records) {
      markers[date] = records.map((record) => {
        'emotion': record.emotionType,
        'intensity': record.intensity,
      }).toList();
    });
    
    return markers;
  }
}